import { _decorator, Component, instantiate, Label, Color, Prefab } from 'cc';
import { GameData } from './GameData';
import { gameEvent, GameEventType, GameStorage, GameTimer, StorageKey } from './Global';
const { ccclass, property } = _decorator;

/**
 * 文字容器
 */
@ccclass('TextContent')
export class TextContent extends Component {

    @property({ type: Prefab, visible: true })
    textPrefab: Prefab = null;
    start() {

        this.restart()


    }
    protected onLoad(): void {
        gameEvent.on(GameEventType.CODE_CLICK, this.onCodeCheck, this);
    }

    onEnable() {
        // gameEvent.on('clickCode', this.onCodeCheck, this);
    }

    onDisable() {
        gameEvent.off(GameEventType.CODE_CLICK, this.onCodeCheck, this);
    }

    update(deltaTime: number) {

    }

    restart() {
        // 清空所有子节点
        this.node.removeAllChildren();
        // 添加新的文字节点
        GameData.lineWords.split('').forEach((char, index) => {
            const textNode = instantiate(this.textPrefab);
            textNode.name = `text${index}`;
            const label = textNode.getComponent(Label);
            label.string = char
            this.node.addChild(textNode);
        });
    }


    onCodeCheck(char: string) {
        // 如果点击的文字正好是下一个
        if (char === GameData.getNextCode()) {
            this.matchSuccess(char)
            if (GameData.isSuccess()) {
                // 成功通关
                GameTimer.pause();
                gameEvent.emit(GameEventType.GAME_SUCCESS, GameEventType.GAME_SUCCESS);

                // 统计游戏时间
                this.countTime();
            }
        } else {
            GameTimer.pause();
            setTimeout(() => {
                gameEvent.emit(GameEventType.GAME_TIMER_STOP, GameEventType.GAME_TIMER_STOP);
            }, 1000)
        }
    }

    matchSuccess(char: string) {
        GameData.answerWords += char;

        // 把已配对的文字置为黑色
        const textNode = this.node.getChildByName(`text${GameData.answerWords.length - 1}`);
        const label = textNode.getComponent(Label);
        label.color = Color.BLACK


        // 特殊处理，如果后面遇到 ，。也要置为黑色
        const nextChar = GameData.getNextCode();
        if (nextChar === '，' || nextChar === '。') {
            this.matchSuccess(nextChar)
        }
    }

    // 统计游戏时间
    countTime() {
        let level = GameStorage.getItem(StorageKey.LEVEL) || 1;

        // 统计上一关的时间
        const game_time_str = GameStorage.getItem(StorageKey.GAME_TIME) || '[]';
        try {
            // 就是一个number[]
            const game_time = JSON.parse(game_time_str);
            game_time[level - 1] = 30 - GameTimer.time
            GameStorage.setItem(StorageKey.GAME_TIME, JSON.stringify(game_time));

        } catch (error) {
        }
    }

}
